package com.hr.controller;

import com.hr.dto.Result;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.UUID;

@CrossOrigin
@RestController
public class FileController {

    @PostMapping("/uploadFile")
    public Result uploadFile(MultipartFile file, HttpServletRequest request) throws IOException {
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf('.'));
        String newFileName = UUID.randomUUID().toString() + suffix;

        String realPath = request.getServletContext().getRealPath("/pic");
        File f = new File(realPath);
        if(!f.exists()){
            f.mkdirs();
        }

        String absolutePath = realPath + "/" + newFileName;
        String relativePath = "/pic/" + newFileName;
        file.transferTo(new File(absolutePath));

        HashMap<String, String> map = new HashMap<>();
        map.put("bookAddress", absolutePath);
        map.put("bookUrl", relativePath);

        return Result.ok(map);
    }
}
